// pages/circleHome/circleHome.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { jump,getStorage,setStorage, getBarAndTitleHeight } from "../../utils/utils";
// 引入动画插件
import lottie from './lottie'

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: {},
    // 轮播图数据
    bannerList:[],
    // 圈子推荐数据
    circleReferList:[],
     //  标签页选中项
     tabIndex:'1',
     // 帖子列表
     postList: [],
     page: 1,
     total: 0,
     isDone: false,
     //内容动态高度
     contentHeight:0,
     // 类型初始滑动位置
     typeScrollX: 0,
     // 分享类型 1-- 右上角系统分享 2-- 帖子分享
     shareType: 1,
     // 分享内容
     shareInfo: {
       title: '我在圈子上发现了新内容，快来看看',
       path: '/pages/circleHome/circleHome',
       imageUrl: 'https://image-classify.daieco.com/kejian-quanzi/qpUkToC5kE4bffc4952cbd9cd5b16b5ec0863e5c733e.png'
     },
    // 投票征稿期间展示引导提示
    showTips: false,
    // 页面滚动高度
    scrollTop: 0,
    // 信号栏高度
    ...getBarAndTitleHeight(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
    this.getBannerList()
    this.getReferList()
    this.getList(1)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initAnimate()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar?.()?.setData?.({
			selected: 1,
    })
    // 用户信息
    this.setData({
			userInfo: app.userInfo()
		})
   // 发布帖子之后刷新页面
   if (this.isFromPublish) {
    this.isFromPublish = false
    this.setData({
      page: 1,
      isDone: false,
    })
    wx.pageScrollTo({
      scrollTop: 0
    })
    this.getList(1)
   }
   this.getTime()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 页面滚动
   */
  onPageScroll(e) {
		const scrollTop = e.scrollTop
		this.setData({
			scrollTop
		})
	},

  /**
   * 获取轮播图列表
   */
  async getBannerList(){
     const res=await request.get(api.circleAdSpace,{
        size: 999
     },{loading: false})
     if(res.httpStatus==200){
      this.setData({
        bannerList: res?.data.records
      })
     }
  },
  /**
   * 获取圈子推荐列表
   */
  async getReferList(){
     const res=await request.get(api.circleList,{
        size: 4
     },{loading: false})
     if(res.httpStatus==200){
      this.setData({
        circleReferList:res?.data.records
      })
     }
  },
  /**
   * 获取帖子列表
   * @param {*} page 当前页
   */
  async getList(page) {
    const { tabIndex } = this.data
    const res = await request.get(api.circlePostList, {
      page,
      size: 10,
      type: tabIndex
    }, { loading: true })
    const data = (res?.data?.records || []).map(item => {
      item.picUrls = (item?.picUrls || []).filter(Boolean)
      let picUrls = item.picUrls.slice(0, 3)
      return {
        ...item,
        picUrls,
        picMore: item?.picUrls?.length - picUrls.length
      }
    })
    this.setData({
      postList: page === 1 ? data : [
        ...this.data.postList,
        ...data,
      ],
      total: res?.data?.pages
    })
    wx.stopPullDownRefresh()
  },
   // 获取活动时间
  async getTime(){
        let res = await request.get(api.voteWaitTime,{},{ loading: false })
        if(res.httpStatus === 200){
          let startDate = res.data.startDate + ' ' + '00:00:00'
          let endDate = res.data.endDate + ' ' + '00:00:00'
          if((new Date().getTime() >= new Date(startDate.replace(/-/g, "/")).getTime()) && (new Date().getTime() < new Date(endDate.replace(/-/g, "/")).getTime())){
            this.setData({
              showTips: true
            })
          }else{
            this.setData({
              showTips: false
           })
          }
        }
  },
  // 标签页选中变化
  switchNav(e) {
    const tabIndex = e?.currentTarget?.dataset?.index
     this.setData({
       tabIndex
     })
     this.getList(1)
     wx.pageScrollTo({
       scrollTop: 0
     })
  },
   // 类型滑动开始
   typeTouchStart(event) {
    this.setData({
      typeScrollX: event?.touches?.[0]?.pageX || 0
    })
  },
  // 类型滑动移动
  typeTouchMove(event) {
    const { typeScrollX } = this.data
    const currentX = event?.touches?.[0]?.pageX || 0

    if (typeScrollX - currentX > 50) {
      console.log('右滑')
      this.touchType = 'right'
    } 
    if (currentX - typeScrollX > 50) {
      console.log('左滑')
      this.touchType = 'left'
    }
  },
  // 类型滑动结束
  typeTouchEnd() {
    if (!this.touchType) return
    const {tabIndex } = this.data
    const typeList = ['1', '2', '3']
    const lastIndex = typeList.length - 1
    let currentIndex = typeList.indexOf(tabIndex)

    if (this.touchType === 'left') {
      currentIndex--
      currentIndex = currentIndex < 0 ? 0 : currentIndex
    }
    if (this.touchType === 'right') {
      currentIndex++
      currentIndex = currentIndex > lastIndex ? lastIndex : currentIndex
    }

    if (typeList[currentIndex] !== tabIndex && !this.refresh) {
      this.setData({
        tabIndex: typeList[currentIndex]
      })
      this.getList(1)
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    this.touchType = null
  },
  // 跳转到个人中心页面
  jumpPersonalCenter(){
    let check = this.checkIsLogin()
    if(!check){
      jump('home',{ id: app.userId() })
    }
  },
  // 跳转到圈子搜索页面
  jumpCircleSearch(){
    let check = this.checkIsLogin()
    if(!check){
      jump('circleSearch')
    }
    
  },
  // 跳转到轮播图自定义路径
  jumpCustomPath(e){
    let check = this.checkIsLogin()
    if(!check){
      if(!e.currentTarget?.dataset?.path) return
      wx.navigateTo({
        url: e.currentTarget.dataset.path,
        fail:(e)=>{
          wx.showToast({
            title: e,
            icon:'none'
          })
        }
      })
    }
  },
  // 跳转到圈子列表页面
  jumpCircleList(){
    let check = this.checkIsLogin()
    if(!check){
      jump('circleList')
    }
  },
  //打开圈子详情页面
  async jumpCircleDetail(e){
    let check = this.checkIsLogin()
    if(!check){
      if (this.loading) return
      this.loading = true
      const id = e?.currentTarget?.dataset?.id
      const res = await request.get(api.circleDetail, { id }, { loading: false })
      if (!res?.data?.allow) {
        wx.showToast({
          icon: 'none',
          title: '抱歉，您没有访问权限',
          duration: 2000
        })
      } else {
        jump('circle', { id })
      }
      this.loading = false

    }
  },
  // 跳转到发帖页面
  jumpPost() {
    let check = this.checkIsLogin()
    if(!check){
      this.isFromPublish = true
      jump('publish')
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      isDone: false,
    })
    this.getBannerList()
    this.getReferList()
    this.getList(1)
  },

  // 通过分享进入验证登录
  checkIsLogin:function(){
    if (!app.isLogin()) {
      setStorage('redirectPath', '/pages/circleHome/circleHome')
      app.login()
      return true
    }else{
      return false
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { page, total } = this.data
    if (page < total) {
      page++
      this.setData({
        page
      })
      this.getList(page)
    } else {
      this.setData({
        isDone: true
      })
    }
  },
  // 点击帖子分享
  handleToShare(e){
    let { title, imageUrl, path } = e.detail
    this.setData({
      shareType: 2,
      shareInfo:{
        title,
        imageUrl,
        path
      }
    })
  },
  /**
   * 初始化加载动画
   */
  initAnimate() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#post-btn')
      .node((res) => {
        if(res[0]){
          const canvas = res[0].node
          const context = canvas.getContext('2d')
          canvas.width = 300
          canvas.height = 300
          lottie.setup(canvas)
          this.ani = lottie.loadAnimation({
            loop: true,
            autoplay: true,
            animationData: require('./data.js'),
            rendererSettings: {
              context,
            },
          })
          this.inited = true
        }
      })
      .exec()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let { shareType, shareInfo } = this.data
    let { title, path, imageUrl } = shareInfo
    const userId = getStorage('userId') || ''
    if(shareType === 1){
      return shareOptions('default', e, '我在圈子上发现了新内容，快来看看', '/pages/circleHome/circleHome?inviteData=' + userId, 'https://image-classify.daieco.com/kejian-quanzi/qpUkToC5kE4bffc4952cbd9cd5b16b5ec0863e5c733e.png')
    }else{
      return new Promise((resolve, reject) => {
        shareOptions(
          'default',
          e,
          resolve({
            title,
            path,
            imageUrl,
          })
        )
        this.setData({
          shareType: 1,
        })
      })
    }
  }
})